<?php
	require_once "config.php";
	
	if ($_POST) {
		// the fun parts...
		if ($_REQUEST['action'] == "add") {
		    $listingid = (isset($_POST['listingid']) ? $_POST['listingid'] : NULL);
            if ($listingid == NULL && empty($listingid)) {
                ErrorMessage::Show("Error","Error adding photo.  No listingid specified");
            }
            else {
                // make sure there's room for another one
                if (ListingImageManager::CountImages($listingid) < SettingManager::GetSetting("listing_images_quota")) {
                    // then we need to take the uploaded image, scale it, save it, and thumbnail it

                    if (isset($_FILES['photo'])) {
                        switch ($_FILES['photo']['error']) {
                            case UPLOAD_ERR_OK:
                                // no error
                                // rename the tmp file to have the right extension
                                $ext = array_pop(explode(".",$_FILES['photo']['name']));
                                rename($_FILES['photo']['tmp_name'],$_FILES['photo']['tmp_name'] . ".$ext");

                                $_FILES['photo']['tmp_name'] .= ".$ext";

                                list($srcx,$srcy) = getimagesize($_FILES['photo']['tmp_name']);
                                list($dstx,$dsty) = array(
                                    SettingManager::GetSetting("listing_images_width"),
                                    SettingManager::GetSetting("listing_images_height")
                                );

                                $image = new Thumbnail($_FILES['photo']['tmp_name'],$dstx,null,RESOURCE);

                                $filename = substr(md5(microtime(true)),0,16);
                                $filename_only = $filename . ".";
                                $filename = Conf::LISTING_IMAGES . "/" . $filename . ".";

                                $format = SettingManager::GetSetting("listing_images_format");
                                switch ($format) {
                                    case "png":
                                        $filename .= "png";
                                        $filename_only .= "png";
                                        break;
                                    case "jpg-50":
                                    case "jpg-75":
                                    case "jpg-100":
                                        $filename .= "jpg";
                                        $filename_only .= "jpg";
                                }

                                if ($format == "png") {
                                    imagepng($image->Render(),$filename);
                                }
                                else {
                                    $quality = array_pop(explode("-",$format));
                                    imagejpeg($image->Render(),$filename,$quality);
                                }


                                // add the photo to the database
                                $bld = array(
                                    "listingid" => $_POST['listingid'],
                                    "imagename" => $filename_only,
                                    "upload_date" => time()
                                );
                                DBM::Execute(QueryTools::CreateQuery($bld,"listing_images","insert"));
                                header("Location: photos.php?id=$_POST[listingid]");
                            break;
                            case UPLOAD_ERR_INI_SIZE:
                            case UPLOAD_ERR_FORM_SIZE:
                                ErrorMessage::Show("Error - Too Big","Sorry, the file you uploaded was larger than the maximum allowed size.");
                            break;
                            case UPLOAD_ERR_PARTIAL:
                            case UPLOAD_ERR_NO_FILE:
                                ErrorMessage::Show("Error - Upload Failed","Sorry, your file was not fully received.  Please try again.");
                            break;
                            case UPLOAD_ERR_NO_TMP_DIR:
                            case UPLOAD_ERR_CANT_WRITE:
                                ErrorMessage::Show("Error - Couldn't Upload","Sorry, your file could not be saved.  Please try again later or contact us for assistance.");
                            break;
                            case UPLOAD_ERR_EXTENSION:
                            default:
                                // unknown error
                        }
                    }
                }
                else {
                    ErrorMessage::Show("Error","You cannot add any more photos to this listing");
                }
            }
		}
		else if ($_REQUEST['action'] == 'remove') { 
            if (AuthManager::ListingBelongsTo($_POST['listingid']) || AuthManager::CheckPermissions(AuthConstants::ADMINISTRATORS)) {
                // get the imagename first:
                $info = DBM::FetchRow("SELECT * FROM listing_images WHERE id=$_POST[photoid];");
                if (isset($info)) {
                    // imagename
                    $filename = Conf::GetImageDir() . "/$info[imagename]";
                    unlink($filename);

                    DBM::Execute("DELETE FROM listing_images WHERE id=$_POST[photoid]");
                }
            }
            header("Location: photos.php?id=$_POST[listingid]");
		}
		else if ($_REQUEST['action'] == 'update') {
		    $listingid = $_POST['listingid'];
            echo "<pre>" . print_r($_POST,true) . "</pre>";
            if (AuthManager::ListingBelongsTo($listingid) || AuthManager::CheckPermissions(AuthConstants::ADMINISTRATORS)) {
                $bld = array("comment" => $_POST['comment']);
                $query = QueryTools::CreateQuery($bld,"listing_images","update",$_POST['photoid']);
                DBM::Execute($query);

                header("Location: photos.php?id=$_POST[listingid]");
            }
            else {
                header("Location: index.php");
            }
		}
		else {}
	}
	else {
		Functions::PrintHeader("Edit Photos");
		
		if (!isset($_GET['id']) || empty($_GET['id'])) {
			ErrorMessage::Show("Error, No Listing Specified","No listing was specified.  Please hit back and try again.");
		}
		else if (!AuthManager::CheckPermissions(AuthConstants::ADMINISTRATORS) && !AuthManager::ListingBelongsTo($GET['id'])) {
			ErrorMessage::Show("Permissions Error","Sorry, you don't have permission to edit this listing.");
		}
        else if (DBM::CountRows("SELECT * FROM listings WHERE id=$_GET[id]") == 0) {
            ErrorMessage::Show("Error, No Such Listing","No listing exists with ID $_GET[id]");
        }
		else {
			$maxphotos = SettingManager::GetSetting("listing_images_quota");
			$breakat = SettingManager::GetSetting("listing_images_per_row");
			$existing_photos = ListingImageManager::GetImages($_GET['id']);
			$count = 0;

            $lr = new ListingRow($_GET['id']);
            $lr->Render();
			?>
            <br /><br />

			<table class='wide cgltable'>
            <thead>
				<tr>
					<th colspan='<?=$breakat?>'>Listing Photos</th>
				</tr>
            </thead>

				<?php
				foreach ($existing_photos as $imagename => $photo) {
                    $thumbnail = ListingImageManager::ThumbnailOf($photo);
                    $image = DBM::FetchRow("SELECT * FROM listing_images WHERE imagename LIKE '$imagename';");
                    $photoid = $image['id'];

                    $comment = stripslashes($image['comment']);
				?>
				<td>

				    <form method="POST" action="photos.php?action=remove">
                        <input type='hidden' name='listingid' value='<?=$_GET['id']?>' />
                        <input type='hidden' name='photoid' value='<?=$photoid?>' />
				        <div style='text-align:center;'>
                            <img src='<?=$thumbnail?>' /><br />
					        <input type='submit' class='remove' value='Delete Photo' />
                        </div>
					</form> 
                    <br />
                    <br />
                    <hr />
                            
                    <form method="POST" action="photos.php?action=update">
					    <div>
                            <input type='hidden' name='listingid' value='<?=$_GET['id']?>' />
                            <input type='hidden' name='photoid' value='<?=$photoid?>' />
						    <textarea name='comment'><?=$comment?></textarea>
                            <input style='display:block;' type='submit' value='Update Comment' />
                        </div>
                    </form>
				</td>
				<?php
					if ($count % $breakat == 0 && $count > 0)
						echo "</tr><tr>";
						
					$count++;
				}
				for ($x = $count; $x < $maxphotos; $x++) {
				?>
				<td>
					<form method="POST" enctype="multipart/form-data" action="photos.php?action=add">
                        <input type='hidden' name='listingid' value='<?=$_GET['id']?>' />
						<div style='text-align:center;'>
						<img src='<?=ThemeManager::GetImage('nophotos')?>' alt='no image specified'>
						</div>
						<br />
						<input type='file' name='photo' />
						<br />
						<input type='submit' class='add' value='Upload Photo' />
					</form>
				</td>
				<?php
				}
				?>
				</tr>
			</table>
			<?php	
		}
		
		Functions::PrintFooter();
	}
?>
